<template>
    <!-- 机械发料修改 -->
    <div class="e-form">
        <div class="tabs" v-if="Object.keys(basicFormData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="发料明细"
                    name="receivingMaterials"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <BillTop title="机械发料编辑" @cancel="cancel"></BillTop>
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="basicFormData"
                                        label-width="150px"
                                        ref="ruleForm"
                                        :rules="rules"
                                        class="demo-ruleForm"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="发料编号："
                                                >
                                                    {{ basicFormData.billNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="发料人员："
                                                >
                                                    {{
                                                        basicFormData.issuingPersonnelName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="机构：">
                                                    {{ basicFormData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="发料日期："
                                                    prop="issueDate"
                                                >
                                                    <el-date-picker
                                                    v-if="basicFormData.redBillState !='3' "
                                                        v-model="
                                                            basicFormData.issueDate
                                                        "
                                                        type="date"
                                                        placeholder="选择日期："
                                                        value-format="yyyy-MM-dd"
                                                        :clearable="false"
                                                    >
                                                    </el-date-picker>
                                                    <span  v-else>{{basicFormData.issueDate}}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="发料数量："
                                                >
                                                    {{
                                                        basicFormData.issuedQuantity
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="状态：">
                                                    {{
                                                        [
                                                            '草稿',
                                                            '审核中',
                                                            '已审核',
                                                            '已关闭',
                                                            '',
                                                            '已作废'
                                                        ][basicFormData.state]
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <!-- 发生冲红单业务时，才显示 -->
                                             <el-form-item label="冲红单：" v-if="basicFormData.redBillId != null &&basicFormData.redBillNo != null &&basicFormData.redBillState != ''">
                                                    <span
                                                        :style="
                                                            redBillStateStyle
                                                        "
                                                        >{{
                                                            redBillStateFun
                                                        }}</span
                                                    >
                                                </el-form-item>
                                        </el-row>
                                        <el-row>
                                            <el-form-item label="备注：">
                                                <el-input
                                                    type="textarea"
                                                    :rows="2"
                                                    placeholder="请输入内容"
                                                    v-model="
                                                        basicFormData.remarks
                                                    "
                                                >
                                                </el-input>
                                            </el-form-item>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>

                        <!-- ------------------------------------------------------------------------------------- -->
                    </div>

                    <!-- 发料明细 -->
                    <div id="receivingMaterialsCon" class="con">
                        <div class="tabs-title" id="receivingMaterials">
                            发料明细
                        </div>
                       <div class="e-table">
                            <div class="top" v-if="basicFormData.redBillState != '3'">
                                <div class="left">
                                    <div>
                                         <el-button
                                        size="small"
                                        style="background: rgb(75, 178, 255); color: #fff"
                                        @click="selectEquip"
                                        >选择设备</el-button
                                    >
                                    </div>

                                </div>
                            </div>

                            <el-table
                                class="table"
                                ref="planTable"
                                :data="planRepairDtlList"
                                border
                                style="width: 100%"
                                @selection-change="planTableSelect"
                                :row-class-name="tableRowClass"
                                :max-height="$store.state.tableHeight"
                v-sortTable="{ 'tableData': planRepairDtlList, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column type="selection" width="55" align="center" v-if="isBatch[0].flag">
                                </el-table-column>
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70" v-if="basicFormData.redBillState !='3' ">
                                    <template slot-scope="{ row }">
                                          <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="handleDelete(row)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="equipNumber"
                                    label="设备编号"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                  <template slot-scope="scope">
                                    <span
                                        @click="showTable(scope.row)"
                                        style="color: blue; cursor: pointer"
                                    >
                                        {{ scope.row.equipNumber }}
                                    </span>
                                    </template>
                                </el-table-column>
                                <el-table-column  prop="equipName" label="设备名称"  min-width="200"
                                    show-overflow-tooltip align="center">
                                </el-table-column>

                                <el-table-column
                                    prop="spec"
                                    label="规格型号"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="operatorName"
                                    label="当前操作手"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                <template  slot="header">
                                    <span>当前操作手</span>
                                    <el-button
                                    v-if="basicFormData.redBillState != '3'"
                                        type="mini"
                                        style="background: #2e61d7;color:#fff;"
                                        v-debounce
                                        @click="goEquipOperatorName"
                                        >登记</el-button
                                    >
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="remarks"
                                    label="备注"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                 <template slot-scope="{ row }">
                                    <el-input
                                    v-if="basicFormData.redBillState != '3'"
                                        @input="input(row)"
                                        v-model="row.remarks"
                                        clearable
                                    ></el-input>
                                    <span>{{row.remarks}}</span>
                                </template>
                                </el-table-column>

                            </el-table>

                             <!-- 子列表 -->
                             <div v-if="show" style="width: 100%; margin-top: 20px">
                              <div  class="top" v-if="basicFormData.redBillState != '3'">
                                <div class="left">
                                    <div>
                                    <el-button
                                        size="small"
                                        style="background: rgb(75, 178, 255); color: #fff"
                                        @click="selectMaterial"
                                        >选择库存</el-button
                                    >
                                           </div>
                                </div>
                           </div>
                        <div class="errorMsg" v-if="errorMsg.length>0">
                                <span v-for="item,index in errorMsg" :key="index">
                                    {{item}}
                                </span>
                            </div>
                    <el-table
                    class="table"
                      :data="SonPlanRepairDtlList"
                      border
                      :row-class-name="tableRowClassNames"
                      @cell-mouse-enter="cellMouseEnter"
                      @cell-mouse-leave="cellMouseLeave"
                      :cell-class-name="cellClsNm"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                      @selection-change="planTableSelect"
                       :tree-props="{
                        children: 'children',
                        hasChildren: 'hasChildren',
                        }"
                       row-key="uuid"
                       :max-height="$store.state.tableHeight"
                        ref="table"
                v-sortTable="{ 'tableData': SonPlanRepairDtlList, '_this': this, 'ref': 'table' }"
                    >
                      <el-table-column
                        label="操作"
                        fixed
                        width="100px"
                        align="left"
                        v-if="basicFormData.redBillState != '3'"
                      >
                          <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style=" cursor: pointer;">
                                                <img src="@/assets/btn/delete.png"  @click="deleteEle(row)"  v-if="$index > 0&& row.billId">
                                            </div>
                                        </div>
                                    </template>
                      </el-table-column>
                      <el-table-column
                        prop="materialClassName"
                        label="类别"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column prop="spec" label="规格" width="100">
                      </el-table-column>
                       <el-table-column
                        prop="texture"
                        label="材质"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column prop="unit" label="单位" width="100">
                      </el-table-column>

                      <el-table-column
                        prop="warehouseName"
                        label="仓库"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="inventoryQuantity"
                        label="库存数量"
                        width="100"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="collectedQuantity"
                        label="领用数量"
                        width="130"
                      >
                        <template slot-scope="{ row,$index  }">
                          <el-input

                            @input="input(row)"
                            @blur="totalIssuedQuantity"
                            v-model="row.collectedQuantity"
                              v-if="$index > 0 && basicFormData.redBillState != '3'&& row.billId"
                            clearable
                          ></el-input>
                          <span v-else>{{row.collectedQuantity}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="price"
                        label="单价（元）"
                        width="130"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="amount"
                        label="金额（元）"
                        width="130"
                      >
                      <!-- 计算，领用数量*单价，保留两位小数 -->
                      </el-table-column>
                         <el-table-column
                        prop="aaa"
                        label="转换单位"
                        width="130"
                      >
                      <!-- 计算，领用数量*单价，保留两位小数 -->
                      </el-table-column>
                    </el-table>
                             </div>

                        </div>
                    </div>

                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="material"
                            v-if="objFlag.flag5"
                        />
                        <div class="seize-a-seat" v-else>
                            <i class="el-icon-loading"></i>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                      <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                        <ComAuditHistoryIndex
                            :tableData.sync="auditHistoryTable"
                            @getAuditHistory="getAuditHistory"
                            ref="AuditHistoryRef"
                        />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <!-- <div class="buttons">
             <el-button
                type="primary"
                style="background: #2e61d7"
                v-debounce
                v-if="state === '1'"
                >打印</el-button
            >
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="save()"
                v-debounce
                >保存</el-button
            >
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="submit()"
                v-debounce
                >保存并提交</el-button
            >
            <el-button
                type="primary"
                class="btn-delete"
                v-debounce
                v-if="state === '1'"
                @click="nullify()"
                >作废</el-button
            >
            <el-button type="danger" size="small" @click="ctDelete" v-debounce v-if="state === '0'"
                >删除</el-button
            >
            <el-button @click="cancel()">关闭</el-button>
        </div> -->
        <div class="buttons">
              <el-button
                type="primary"
                style="background: #2e61d7"
                v-debounce
                v-if="state === '1'"
                >打印</el-button
            >
               <ComExaButtons
                v-if="basicFormData.state != 5"
                :auditState="auditState"
                :state="basicFormData.state"
                 :founderId="founderId"
                @exas="exas"
            />
            <!-- <el-button
                type="primary"
                class="btn-delete"
                v-debounce
                v-if="state === '1'"
                @click="nullify()"
                >作废</el-button
            > -->
            <el-button @click="cancel" size="small">取消</el-button>
        </div>

    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import AttachComp from '@/components/common/attachIndex'
import Api from '@/api/materials/mechanicalStoreIssue.js'
import CommonApi from '@/api/materials/common.js'
import {  selectDataClient, getUuid, openAppClient } from '@/utils/common'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            auditState: {}, //按钮状态
            isBatch: [
                {
                    flag: false,
                    batch: '进入批量管理'
                },
                {
                    flag: false,
                    batch: '进入批量管理'
                }
            ],

            show: true, //子列表
            tableData: [],
            auditHistoryTable: [], //审核历史
            planRepairDtlList: [], //计划明细表格传后端
            planRepairDtlListCopy: [], //列表显示
            SonPlanRepairDtlList: [], //子列表
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'billId': '',
                'billNo': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'isRed': 0,
                'issueDate': '',
                'issuedQuantity': 0,
                'issuingPersonnelId': '',
                'issuingPersonnelName': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'redBillId': '',
                'redBillNo': '',
                'redBillState': '',
                'remarks': '',
                'sourceId': '',
                'sourceNumber': '',
                'state': '',
                'workId': ''
            },
            objFlag: {
                flag5: false
            },
            currentRow: {},
            id: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            dtlId: '',
            auditParams: {
                billId: this.$route.query.billid, //单据Id  ***
                billType: '1010', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgId, //单据机构Id
                orgName: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgName, //单据机构名称
                userId: localStorage.getItem('userId'), //审核人Id    ***
                workId: '', //流程Id
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 1010,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            //验证
            rules: {
                issueDate: [
                    {
                        required: true,
                        message: '请选择发料日期',
                        trigger: 'change'
                    }
                ]
            },
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        'basicFormData.redBillState' () {
            if (this.basicFormData.redBillState == '3') {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.basicFormData.redBillState == '0' ||
                this.basicFormData.redBillState == '1'
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.basicFormData.redBillState == '2') {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        }
    },
    computed: {
        //当前单据状态
        state () {
            return this.basicFormData.state
        },
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billid
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.basicFormData.redBillState) {
            case '0':
                redState = '冲销中'
                break
            case '1':
                redState = '冲销中'
                break
            case '2':
                redState = '已冲销'
                break
            case '3':
                redState = '红单'
                break
            }
            return redState
        }
    },

    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.billid = this.$route.query.billid
        this.getBasicData() //进入页面就获取基本信息数据
        this.getMasterPlan()
        this.getAttach()
        this.getCurrentUnitInfo()
    },

    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        // 获取按钮状态
        getCurrentUnitInfo () {
            CommonApi
                .getCurrentUnitInfo({
                    billId: this.$route.query.billid,
                    billType: 1010,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.undoAudit() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.nullify() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        //作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                CommonApi.nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功', this.cancel, null, this.cancel)
                })
            })
        },
        //撤回
        undoAudit () {
            const params2 = {
                billId: this.billid, //单据Id  ***
                billType: '1010', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: '', //单据机构Id
                orgName: '', //单据机构名称
                userId: this.userId, //审核人Id    ***
                workId: '', //流程Id
            }
            CommonApi.undoAudit(params2).then(() => {
                this.clientPop('suc', '撤回成功！', this.cancel, null, this.cancel)
            })
        },
        //汇总明细  金额
        totalAmount () {
            this.SonPlanRepairDtlList.forEach(a=>{
                a.children.forEach(item=>{
                    item.amount = item.collectedQuantity * item.price
                    item.amount = item.amount.toFixed(2)
                })
            })

        },
        //汇总发料数量
        totalIssuedQuantity () {
            let num = 0
            this.SonPlanRepairDtlList.forEach(a=>{
                a.children.forEach(item=>{
                    num += parseInt(item.collectedQuantity)
                    item.amount = item.collectedQuantity * item.price
                    item.amount = item.amount.toFixed(2)
                })
            })
            this.basicFormData.issuedQuantity = num
        },
        //点击登记
        goEquipOperatorName () {
            openAppClient('/operatorList', '登记操作手', function () {
            })
        },
        //是否进入批量管理
        batchOperation (name) {
            switch(name) {
            case 'planDetail':
                this.isBatch[0].flag = !this.isBatch[0].flag
                if(this.isBatch) {
                    this.isBatch[0].batch = '退出批量管理'
                    this.$refs.planTable.clearSelection()
                }else{
                    this.isBatch[0].batch = '进入批量管理'
                }
                break
            case 'changeHistory':
                this.isBatch[1].flag = !this.isBatch[1].flag
                if(this.isBatch) {
                    this.isBatch[1].batch = '退出批量管理'
                    this.$refs.changeHistorySelect.clearSelection()
                }else{
                    this.isBatch[1].batch = '进入批量管理'
                }
                break
            }

        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //获取基本信息数据
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/mechanicalMaterialIssuance/findById',
                    params: {
                        id: this.billid
                    }
                })
                .then(res => {
                    this.basicFormData = res
                })
        },
        //获取明细信息
        getMasterPlan () {
            this.$Ajax
                .httpGet({
                    url: '/material/mechanicalMaterialIssuance/getDtlListById',
                    params: {
                        id: this.billid,
                    },
                }).then(res=>{
                    console.log('res', res)
                    res.forEach(item=>{
                        // this.planRepairDtlListCopy.push(item)
                        this.planRepairDtlList.push(item)
                        this.dtlId = item.dtlId
                        //this.SonPlanRepairDtlList = item.children
                        item.children.forEach(a=>{
                            a.materialClassName = a.topClassName
                            a.uuid = getUuid()
                            a.children.forEach(i => {
                                i.uuid = i.dtlId
                            })
                            const count = a.children.reduce(
                                (prev, c) => (prev += c.designQuantity || 0),
                                0
                            )
                            a.materialName = `小计： ${count}`
                        })
                        this.SonPlanRepairDtlList = item.children
                    })
                })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
                        document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //选择设备
        selectEquip () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/facilityaccount/account/all/equipment', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({
                    'orgId': this.orgId,
                    'states': []
                }),
                Title: '选择设备台账' // 标题
            }).then(val => {
                this.setSelectedInfo(val)
                this.planRepairDtlList = this.planRepairDtlList ? this.planRepairDtlList : []
                //  this.planRepairDtlListCopy = this.planRepairDtlListCopy ? this.planRepairDtlListCopy : []
                val.forEach(item=>{
                    item.changeType = 1
                    let obj = {
                        'billId': this.billid, //机械发料id
                        'changeType': 1,
                        'dtlId': '', //机械发料设备明细id
                        'equipAccountBillId': item.accountId, //设备台账id
                        'equipId': '', //设备id
                        'equipName': item.equipmentName, //设备名称
                        'equipNumber': item.equipmentNo, //设备编号
                        'operatorId': '', //操作手id
                        'operatorName': '', //操作手名称
                        'remarks': '', //备注
                        'spec': item.specificationModel, //规格
                        'children': [],
                        ...item
                    }
                    this.planRepairDtlList.push(obj)
                    // this.planRepairDtlListCopy.push(obj)
                })
            })
        },
        //点击设备编号显示物资列表
        showTable () {
            this.show = true
        },
        //选择库存
        selectMaterial () {
            let ids = []
            let warehouseType = '0'
            selectDataClient({
                SelectServiceToken: '/material/stock/listUsableInventoryByOrgIdForSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify(warehouseType),    // 接口参数(name为模拟参数)
                Title: '选择库存明细' // 标题
            }).then(val=>{
                this.setSelectedInfo(val)

                const mapObj = {}
                let arr = []
                val.forEach(e => {
                    this.quantity = e.quantity
                    const children = []
                    e.materialClassNameArr = e.materialClassName.split('/')
                    e.materialClassIdArr = e.materialClassId.split('/')
                    // TODO: 统计小计
                    let obj
                    const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                    const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                    if (!mapObj[topClassId]) {
                        obj = {
                            topClassId,
                            topClassName,
                            customId: topClassId,
                            materialClassId: topClassId,
                            materialClassName: topClassName,
                            uuid: getUuid(),
                            totalAmount: null,
                            totalQuantity: null,
                        }
                        //这里需要改成push多个对象   还没改
                        arr.push(obj)

                        mapObj[topClassId] = obj
                    } else {
                        obj = mapObj[topClassId]
                    }

                    // 物资名称
                    children.push({
                        uuid: getUuid(),
                        customId: getUuid(),
                        amount: 0, //	金额(元)
                        billId: this.billid, //	机械发料id
                        changeType: 1, //	变更类型
                        collectedQuantity: 0, //	领用数量
                        dtlId: '', //	机械发料物资明细id
                        equipDtlId: this.dtlId, //	机械发料设备明细id   绑机械发料物资明细id
                        inventoryQuantity: e.quantity, //	库存数量
                        materialClassId: e.materialClassIdArr.join('/'), //	物资类别id
                        materialClassName: e.materialClassNameArr.join('/'), //	物资类别名称)
                        materialId: e.materialId, //	物资id
                        materialName: e.materialName, //	物资名称
                        price: 0, //	单价(元)
                        spec: e.spec, //	规格型号
                        texture: e.texture, //	材质
                        unit: e.unit, //	计量单位
                        warehouseId: e.warehouseId, //	仓库id
                        warehouseName: e.warehouseName, //	仓库名称
                    })
                    obj.children = !obj.children
                        ? children
                        : obj.children.concat(children)
                        // 统计小计
                    const count = obj.children.reduce(
                        (prev, c) => (prev += c.designQuantity || 0),
                        0
                    )
                    obj.materialName = `小计： ${count}`
                    obj.children = this.uniqueArray(obj.children, 'customId')

                })
                this.SonPlanRepairDtlList = arr
                this.totalIssuedQuantity()
                this.totalAmount()
            })
        },
        count_ (obj) {
            return obj.children.reduce((prev, c) => (prev += c.amount || 0), 0)
        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        //把设备下的物资数据合并到设备的children里
        childrenConcart () {
            this.planRepairDtlList.forEach(item=>{
                if( item.changeType === -1) {
                    item.changeType = -1
                }else if(item.changeType === null) {
                    item.changeType = 2
                }

                item.children = this.SonPlanRepairDtlList
            })
            // this.planRepairDtlListCopy.forEach(item=>{
            //     if( item.changeType === -1) {
            //         item.changeType = -1
            //     }else if(item.changeType === null) {
            //         item.changeType = 2
            //     }
            //     item.children = this.SonPlanRepairDtlList
            // })
        },
        //点击删除弹窗
        // deletePlanList () {
        //     const length = this.planSelect.length
        //     if(length === 0) {
        //         this.clientPop(
        //             'info',
        //             '你还未选择数据,请选择!',
        //         )
        //     }else{
        //         this.clientPop(
        //             'info',
        //             `已选择【${length}】条数据，确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。`,
        //             this.delete
        //         )
        //     }

        // },

        //单个删除计划明细
        handleDelete (row) {
            row.changeType = -1
            // if(row.dtlId) {
            //     this.$set(row, 'changeType', -1)
            //     this.planRepairDtlList.splice($index, 1)
            // }else{
            //     this.planRepairDtlList.splice($index, 1)

            // }
        },
        //批量删除计划明细
        // delete () {
        //     // let length = this.errorMsg.length
        //     if (this.planSelect.length > 0) {
        //         this.planSelect.forEach(item=>{
        //             if(item.dtlId) {
        //                 this.$set(item, 'changeType', -1)
        //                 for(let i = this.planRepairDtlListCopy.length; i > 0; i--) {
        //                     if(this.planRepairDtlListCopy[i - 1] === item) {
        //                         this.planRepairDtlListCopy.splice(i - 1, 1)
        //                     }
        //                 }
        //                 //汇总金额
        //                 if (length > 0 ) {
        //                     this.verifyTable()
        //                 }
        //                 this.$refs.planTable.clearSelection()
        //             }else{
        //                 const localArr = []
        //                 localArr.push(item)
        //                 for(let i = this.planRepairDtlList.length; i > 0; i--) {
        //                     for(let j = 0; j < localArr.length; j++) {
        //                         if(this.planRepairDtlList[i - 1] === localArr[j]) {
        //                             this.planRepairDtlList.splice(i - 1, 1)
        //                             //汇总金额
        //                             if (length > 0 ) {
        //                                 this.verifyTable()
        //                             }
        //                         }
        //                         if(this.planRepairDtlListCopy[i - 1] === localArr[j]) {
        //                             this.planRepairDtlListCopy.splice(i - 1, 1)
        //                             //汇总金额
        //                             if (length > 0 ) {
        //                                 this.verifyTable()
        //                             }
        //                         }
        //                     }
        //                 }
        //                 this.$refs.planTable.clearSelection()
        //             }
        //         })
        //     }
        // },
        //删除物资明细
        deleteEle (row) {
            row.changeType = -1
        },
        tableRowClassNames ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //保存按钮
        // save () {
        //     // this.$refs[formName].validate(valid => {
        //     //     if (valid) {
        //     this.childrenConcart()
        //     //基础信息
        //     const p1 = Api.EditMechanicalStoreIssue(
        //         this.basicFormData
        //     )
        //     //明细
        //     const p2 = Api.EditMechanicalStoreIssueList(
        //         this.planRepairDtlList
        //     )
        //     Promise.all([p1, p2]).then(() => {
        //         this.clientPop('suc', '保存成功！', ()=>{
        //             this.getBasicData(),
        //             this.getMasterPlan()
        //         })
        //     })
        //     // } else {
        //     //     return false
        //     // }
        //     // })
        // },
        //提交
        // submit () {
        //     // this.$refs[formName].validate(valid => {
        //     //     if (valid) {
        //     this.childrenConcart()
        //     const params = {
        //         billId: this.billid, //单据Id  ***
        //         billType: '1010', //单据编码  ***
        //         dtls: [], //审核中字段值变更历史
        //         freeNextUnitIndex: 0, //下一步审核步骤
        //         freeNextUser: '', //下一步审核人ID
        //         isPass: true, //审核是否通过
        //         isShareInAudit: true, //是否共享审核节点
        //         opinion: '', //审核意见   ***
        //         orgId: this.orgId, //单据机构Id
        //         orgName: this.orgName, //单据机构名称
        //         userId: this.userId, //审核人Id    ***
        //         workId: '', //流程Id
        //     }
        //     const p1 = Api.EditMechanicalStoreIssue(
        //         this.basicFormData
        //     )
        //     //明细
        //     const p2 = Api.EditMechanicalStoreIssueList(
        //         this.planRepairDtlList
        //     )
        //     const p3 = CommonApi.AuditCommit(params)
        //     Promise.all([p1, p2, p3]).then(() => {
        //         this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
        //     })
        //     //     } else {
        //     //         return false
        //     //     }
        //     // })
        // },
        //保存
        save () {
            this.errorList = []
            this.childrenConcart()
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    this.clientPop('suc', '保存成功', this.$router.go(0))
                })
                .catch(() => {
                    this.scorllError()
                })
        },

        // //保存并提交
        submit () {
            this.errorList = []
            this.childrenConcart()
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    CommonApi.AuditCommit(this.auditParams).then(() => {
                        this.clientPop('suc', '保存并提交成功', this.cancel, null, this.cancel)
                    })
                })
                .catch(() => {
                    this.scorllError()
                })

        },
        // //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {

                        Api.EditMechanicalStoreIssue(this.basicFormData)
                            .then(() => {
                                this.getBasicData() //更新基本信息
                                resolve()
                            })
                            .catch(err => {
                                this.setError('baseInfo')
                                reject(err)
                            })
                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },

        // //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject) => {
                this.verifyTable()

                    .then(() => {
                        Api.EditMechanicalStoreIssueList(this.planRepairDtlList)
                            .then(() => {
                                // this.getMasterPlan() //更新明细
                                resolve()
                            })
                            .catch(err => {
                                this.setError('receivingMaterials')
                                reject(err)
                            })
                    })
                    .catch(err => {
                        this.setError('receivingMaterials')
                        reject(err)

                    })
            })
        },
        //明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                if(this.SonPlanRepairDtlList.length === 0) {
                    let str = '机械发料明细不能为空！'
                    this.errorMsg.push(str)
                }
                else if (this.SonPlanRepairDtlList.length > 0) {

                    this.SonPlanRepairDtlList.forEach(v => {
                        v.children.forEach((item, index) => {
                            if (item.changeType !== -1) {
                                if (item.collectedQuantity === '' || item.collectedQuantity === null) {
                                    let str = `请填写第 ${index + 1} 行的领用数量`
                                    this.errorMsg.push(str)
                                }

                            }
                        })
                    })
                }
                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }

            })
        },
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },

        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //删除单据
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/mechanicalMaterialIssuance/delete',
                    params: {
                        id: this.billid
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.cancel)
                    }
                })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //获取审核历史列表
        getAuditHistory () {
            const params = {
                billId: this.billid,
                billType: '1010',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: '',
            }
            CommonApi.getAuditHistory(params).then(res => {
                this.auditHistoryTable = res
            })
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //获取计划明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //如果是-1就隐藏
        tableRowClass ({ row }) {
            if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //监听明细数据input事件
        input (row) {
            if(row.changeType === 1) {
                row.changeType = 1
            }else{

                row.changeType = 2
            }
            // quantity  所有设备领用合计不允许超过库存。
            console.log('this.SonPlanRepairDtlList', this.SonPlanRepairDtlList)
            let num = 0
            this.SonPlanRepairDtlList.forEach(a=>{
                a.children.forEach(item=>{
                    num +=  parseInt(item.collectedQuantity)
                })
            })
            if(num > this.quantity) {
                this.clientPop(
                    'err',
                    '所有设备领用数量合计不允许超过库存数量！',
                )
                setTimeout(()=>{
                    row.acceptedQuantity = 0
                })

            }
        },
        //关闭
        cancel () {
            this.dialogVisible = false
            this.$router.replace('./mechanicalStoreIssue')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'receivingMaterials',
            'accessory',
            'auditHistory'
        ]
        this.tabArr = arr //标星星
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
                    document.documentElement.scrollTop ||
                    document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
</style>
